<?php
/**
 * Created by PhpStorm.
 * User: king
 * Date: 2018/5/12
 * Time: 下午6:00
 */

namespace App\Http\Middleware;

use Closure;
use Spatie\Permission\Exceptions\UnauthorizedException;

/**
 * 权限拦截中间件
 *
 * Class RBACMiddleware
 * @package App\Http\Middleware
 */
class RBACMiddleware
{
    const SUPER_ROLE = 'super_admin';

    /**
     * @param $request
     * @param Closure $next
     * @param null $guard
     * @return mixed|null
     * @throws \Throwable
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $user = auth()->user();

        if (!$user) {
            return null;
        }

        // 如果是超级管理员，放行
        if ($user->hasRole(static::SUPER_ROLE)) {
            return $next($request);
        }

        $info = $request->route()->getActionName();
        $permission = class_basename($info);

        throw_if(
            !$user->can($permission) || !$user->isAvailable(),
            new UnauthorizedException(403)
        );

        return $next($request);
    }
}